package li.com.springaidemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import li.com.springaidemo.common.R;
import li.com.springaidemo.pojo.User;
import li.com.springaidemo.service.UserService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }
//登录
    @PostMapping("/login")
    public R login(@RequestBody User user) {
        System.out.println("开始登录");
        User login = userService.login(user);
        System.out.println("登录成功");
        return R.success(login);
    }
//注册
    @PostMapping("/register")
    public R register(@RequestBody User user){
        User one = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (one!=null){
            return R.error("用户名已存在");
        }
        userService.register(user);
        return R.success("注册成功");
    }
//退出登录
    @PostMapping("/logout")
    public R logout(@RequestBody User user) {
        System.out.println(user.getName());
        userService.logout(user);
        return R.success();
    }
//获取全部用户信息
    @GetMapping("/page")
    public R getUserList(@RequestParam(value = "input")String input){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        if(!input.equals("")){
            queryWrapper.eq("id",input).or().like("name",input).or().like("username",input);
        }
        List<User> list = userService.list(queryWrapper);
        return R.success(list);
    }
//修改|添加个人信息
    @PostMapping("/updateUser")
    public R updateUser(@RequestBody User user){
        if(user.getId()!=null){
            userService.updateById(user);
        }else {
            userService.save(user);
        }
        return R.success();
    }
//删除用户
    @PostMapping("/deleteUser")
    public R deleteUser(@RequestBody User user){
        userService.getBaseMapper().deleteById(user);
        return R.success();
    }
}
